<?php

/*
	Class: Commerce_Magento_Catalog

	About: Author
		Tyler Vigeant, Rich Joslin, Swift Collective

	About: License
		<http://communit.as/docs/license>
*/
class Magento_Curl_Catalog extends Commerce_Db_Model_Magento {
	
	public $debug_mode = false;
	public $locale_code = '';
	
	protected $primary_url = 'communitas/catalog/product/';
	protected $user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)';
	
	private $_scheme = NULL;
	private $_host	 = NULL;
	private $_locale = NULL;
	
	public function __construct(){
		$this->session = new Zend_Session_Namespace('Cts_Temp');
		$this->_scheme = Cts_Registry::get('magento_curl_scheme');
		$this->_host = Cts_Registry::get('magento_curl_host');
	}

	public function setLocale( $code ){
		if( Cts_Registry::get('magento_curl_locale_code')=='1' && !empty($code) ){
			$Catalog = new CommerceMagentoCatalog();
			$this->_locale = $Catalog->formatStoreId( $code );
			
			## Set the class to use (or aquire) the correct session for this locale
			$copy = $this->session->magento_curl_session_id;
			if( is_array($copy) && !array_key_exists($this->_locale, $copy) ){
				## Force _curl() to pull a new session for this locale
				$this->sid = false;
			} elseif( is_array($copy) && array_key_exists($this->_locale, $copy) ){
				## Set the session to this locale
				$this->sid = $copy[ $this->_locale ];
			}
		} else {
			$this->_locale = NULL;
		}
	}

	protected function _curl( $url, $post=NULL ){
		Cts_Log::report("(Catalog) Parsing CURL URL: {$url}", NULL, Zend_Log::INFO);
		if($this->debug_mode) echo "<pre>Parsing URL: {$url}</pre>";
		
		## Parse URL
		$url = parse_url($url);
		
		## Override input with config variables
		$url['scheme'] = $this->_scheme;
		$url['host'] = $this->_host;
		
		// ## Add locale code
		// if( !is_null($this->_locale) ){
		// 	$url['host'] = $url['host'].'/'.$this->_locale;
		// }
		
		## Parse Query
		if( isset($url['query']) ){
			parse_str($url['query'], $url['query']);
		} else {
			$url['query'] = array();
		}
		
		## Set the CURL theme override
		$url['query']['force_curl'] = 'curl';
		
		## Check for session id
		if( !empty($this->sid) ){
			if( !array_key_exists('SID', $url['query']) ){
				$url['query']['SID'] = $this->sid;
			}
		}
		
		## Rebuild Query
		$url['query'] = http_build_query( $url['query'] );
		
		## Rebuild URL
		$curl_url  = $url['scheme'] .'://'. $url['host'] .'/'. $url['path'];
		$curl_url .= (!empty($url['query'])) ? "?{$url['query']}" : '';
		
		if($this->debug_mode) echo "<pre>Connecting to: <a href=\"{$curl_url}\" target=\"_blank\">{$curl_url}</a></pre>";
		
		## Start CURL
		$ch = curl_init(); 
		
		## Set Options
		//curl_setopt($ch, CURLOPT_MUTE,				true); 
		curl_setopt($ch, CURLOPT_URL,				$curl_url); 
		curl_setopt($ch, CURLOPT_HEADER,			false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,	true);
		curl_setopt($ch, CURLOPT_USERAGENT,			$this->user_agent);
		
		## Add POST Data
		if( !is_null($post) ){
			curl_setopt($ch, CURLOPT_POST,			true); 
			curl_setopt($ch, CURLOPT_POSTFIELDS,	$post);
			if($this->debug_mode){
				echo "<pre>Adding post data: \n";
				parse_str($post, $decode);
				var_dump( $decode );
				echo "</pre>";
			}
		}
		
		## Run CURL
		$curl_return = curl_exec($ch);
		$curl_info = curl_getinfo($ch);
		curl_close($ch);
		
		## Return
		if( $curl_return !== false ){
			if($this->debug_mode) echo "<pre>CURL returned status {$curl_info['http_code']} in {$curl_info['total_time']} seconds</pre>";

			switch( $curl_info['http_code'] ){
				case 200:
					$unserialize = @unserialize($curl_return);
					if( !is_array($unserialize) ){
						if($this->debug_mode){
							echo "<pre>CURL results could not be unserialized.\nCURL Results:\n";
							var_dump($curl_return);
							echo '</pre>';
						}
						
						return $curl_return;
					} else {
						if($this->debug_mode){
							echo "<pre>CURL Results:\n";
							var_dump($unserialize);
							echo '</pre>';
						}
						
						if( empty($this->sid) && is_array($unserialize) && isset($unserialize['session_id']) ){
							$this->sid = $unserialize['session_id'];
							
							## If locale is turned on, set a locale specific session ID for Magento
							if( Cts_Registry::get('magento_curl_locale_code')=='1' && !empty($this->_locale) ){
								$locale_session = array( $this->_locale=>$unserialize['session_id'] );
								
								if(!is_array($this->session->magento_curl_session_id)){
									$this->session->magento_curl_session_id = $locale_session;
								} else {
									$this->session->magento_curl_session_id = array_merge($this->session->magento_curl_session_id, $locale_session);
								}
							} else {
								$this->session->magento_curl_session_id = $unserialize['session_id'];
							}
						}
						return $unserialize;
					}
					break;
					
				case 404:
					Cts_Log::report("(Catalog) 404 Page Not Found when attempting to CURL {$curl_info['url']}", NULL, Zend_Log::ERR);
					return false;
					break;
				
				case 500:
					Cts_Log::report("500 Internal Server Error when attempting to CURL {$curl_info['url']}", NULL, Zend_Log::ERR);
					return false;
					break;
			}
		}
		
		Cts_Log::report("An unknown error has occured when attempting to CURL {$curl_info['url']}", NULL, Zend_Log::ERR);
		return false;
	}
	
	public $items		= array();
	public $num_items	= 0;
	public $total		= 0.0;
	public $subtotal	= 0.0;
	public $urls		= array();
	
	public function getProduct($product_id, $attributes = null) {
		if($this->debug_mode) echo "<pre style=\"font-weight: bold;\">:: Getting product data ::</pre>";
		$post = array();
		$post['id'] = $product_id;
		if (!is_null($attributes)) {
			$post['attributes'] = serialize($attributes);
		}
		$post = http_build_query($post);
		$data = $this->_curl('communitas/catalog/product', $post);
		if( is_array($data) && !empty($data) ){
			return $data;
		} else {
			return array();
		}
	}
	
	public function getAttributes($set_id) {
		if($this->debug_mode) echo "<pre style=\"font-weight: bold;\">:: Getting attributes from a set ::</pre>";
		$post = array();
		$post['set_id'] = $set_id;
		$post = http_build_query($post);
		$data = $this->_curl('communitas/catalog/attributes', $post);
		if( is_array($data) && !empty($data) ){
			return $data;
		} else {
			return array();
		}
	}
	
}
